<?php

namespace app\api\controller\Order;

use think\Controller;
use think\Request;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');

        $this->CartModel = model('Product.Cart');

        $this->OrderModel = model('Order.Order');

        $this->OrderProductModel = model('Order.OrderProduct');

        $this->ProductModel = model('Product.Product');

        $this->AddressModel = model('User.Address');

        $this->RecordModel = model('User.Record');
    }

    public function index()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid',0);

            $status = $this->request->param('status',0);

            $where = [
                'userid' => $userid
            ];

            if($status)
            {
                $where['status'] = $status;
            }

            $OrderList = $this->OrderProductModel->with(['Order','product'])->where($where)->select();

            $this->success('返回订单数据',null,$OrderList);
            exit;
        }
    }

    public function add()
    {
        if($this->request->isPost())
        {
            // 接收参数
            $userid = $this->request->param('userid',0);
            $addrid = $this->request->param('addrid',0);
            $cartid = $this->request->param('cartid',0);
            $content = $this->request->param('content','');

            // 查询用户的信息
            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在，请注册');
                exit;
            }

            // 查询收货地址是否存在
            $address = $this->AddressModel->where(['id' => $addrid,'userid' => $userid])->find();

            if(!$address)
            {
                $this->error('收货地址不存在，请重新选择');
                exit;
            }

            // 查询购物车的商品是否存在

            $where = [
                'cart.id' => ['in',$cartid],
                'userid' => $userid
            ];

            $CartList = $this->CartModel->with('product')->where($where)->select();

            if(!$CartList)
            {
                $this->error('选中的商品不存在，请重新选择');
                exit;
            }

            $total = 0;

            foreach($CartList as $item)
            {
                if($item['nums'] > $item['product']['stock'])
                {
                    $this->error($item['product']['name'].'商品库存不足');
                    exit;
                }

                // 用户积分 - 商品的积分
                $price = bcsub($user['point'],$item['total']);

                // 商品的总积分
                $total += $item['total'];

                if($price < 0)
                {
                    $this->error('您的积分不足，请及时充值');
                    exit;
                }
            }

            $this->OrderModel->startTrans();
            $this->UserModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->CartModel->startTrans();
            $this->ProductModel->startTrans();
            $this->RecordModel->startTrans();

            // 订单数据
            $OrderData = [
                'total' => $total,
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code('ask'),
                'content' => $content,
                'status' => 1
            ];

            $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }
            // 订单商品数据
            $OrderProductData = [];

            foreach($CartList as $item)
            {
                $OrderProductData[] = [
                    'orderid' => $this->OrderModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if($OrderProductStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

            // 购物车
            $CartStatus = $this->CartModel->whereIN('id',$cartid)->delete();

            if($CartStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->error('购物车移除失败');
                exit;
            }

            // 商品
            $ProductData = [];

            foreach($CartList as $item)
            {
                $ProductData[] = [
                    'id' => $item['product']['id'],
                    'stock' => bcsub($item['product']['stock'],$item['nums'])
                ];
            }

            $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->CartModel->rollback();
                $this->error('更新库存失败');
                exit;
            }

            // 用户消费记录
            $RecordData = [
                'point' => $total,
                'content' => "订单号：{$OrderData['code']}，消费了{$total}积分",
                'userid' => $userid,
                'state' => 5
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->CartModel->rollback();
                $this->ProductModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 更新用户的积分
            $UserData = [
                'id' => $userid,
                'point' => $price
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
            if($UserStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->CartModel->rollback();
                $this->ProductModel->rollback();
                $this->RecordModel->rollback();
                $this->error('更新用户积分失败');
                exit;
            }

            if($OrderStatus === FALSE && $OrderProductStatus === FALSE && $CartStatus === FALSE && $ProductStatus === FALSE && $RecordStatus === FALSE && $UserStatus === FALSE)
            {
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->CartModel->rollback();
                $this->ProductModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->error('下单失败，请重新下单');
            }else{
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->CartModel->commit();
                $this->ProductModel->commit();
                $this->RecordModel->commit();
                $this->UserModel->commit();
                $this->success('下单成功');
                exit;
            }
            
        }
    }
    // 删除订单
    public function delete()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $orderid = $this->request->param('orderid',0);
            $user = $this->UserModel->find($userid);

        
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $result = $this->OrderProductModel->where(['id' => $orderid])->delete();
            // halt($result);
         

            if ($result === FALSE) {
                $this->error('删除失败');
                exit;
            } else {
                $this->success('删除成功');
                exit;
            }
        }
    }
    // 确认收货
    public function Confirm()
    {
        if($this->request->isPost())
        {
            
        }
    }
}
